<?php

namespace App\Models;

use App\Util\Tool;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;

class CourseCollect extends Model
{
    protected $table='c_course_collects';

    public function course()
    {
        return $this->belongsTo('App\Models\Course');
    }

    /****
     * @param $filter
     * @return int
     * 收藏或取消
     */
    public function setCourseCollect($filter)
    {
        $info = $this->getInfos($filter);
        if (!empty($info)) { //取消收藏
            $res = $this
                ->where("course_id", '=', $filter['course_id'])
                ->where("user_id", '=', $filter['user_id'])
                ->where("work_id", '=', $filter['work_id'])
                ->where("type", '=', $filter['type'])
                ->where("collect_type", '=', $filter['collect_type'])
                ->delete();
            if ($res) {
                return 1;
            } else {
                return 2;
            }
        } else {
            $this->course_id = $filter['course_id'];
            $this->user_id = $filter['user_id'];
            $this->work_id = $filter['work_id'];
            $this->type = $filter['type'];
            $this->collect_type = $filter['collect_type'];
            $this->ins_times =date("Y-m-d",time());
            $res = $this->save();
            if ($res) {
                return 3;
            } else {
                return 4;
            }
        }
    }


    /****
     * @param $data
     * @return mixed
     * 获取收藏列表
     */
    public function getCollectListData($data)
    {
        $where = [];
        $host = new Url();
        $courseCategory =  new CourseCategory();
        $productSort =  new ProductSort();
        $clinic =  new ClinicCategory();
        if (isset($data['type']) && !empty($data['type'])) {
            $where[] = ['c_course_collects.type', '=', $data['type']];
        }
        if (isset($data['collect_type']) && !empty($data['collect_type'])) {
            $where[] = ['c_course_collects.collect_type', '=', $data['collect_type']];
        }
        if (isset($data['type']) && $data['type'] == 1) {
            if (isset($data['title']) && !empty($data['title'])) {
                $where[] = ['c.course_title', 'like', '%' . $data['title'] . '%'];
            }
            $res = $this->join('c_courses as c', 'c.id', '=', 'c_course_collects.course_id')
                ->where([['c_course_collects.user_id', '=', $data['user_id']]])
                ->where($where)
                ->select("*")
                ->get();
        } elseif (isset($data['type']) && $data['type'] == 2) {
            if (isset($data['title']) && !empty($data['title'])) {
                $where[] = ['c.product_name', 'like', '%' . $data['title'] . '%'];
            }
            $res = $this->join('c_product_goods as c', 'c.id', '=', 'c_course_collects.course_id')
                ->where([['c_course_collects.user_id', '=', $data['user_id']]])
                ->where($where)
                ->select("*")
                ->get();
        }elseif (isset($data['type']) && $data['type'] == 3) {
            if (isset($data['title']) && !empty($data['title'])) {
                $where[] = ['c.article_title', 'like', '%' . $data['title'] . '%'];
            }
            $res = $this->join('c_articles as c', 'c.id', '=', 'c_course_collects.course_id')
                ->where([['c_course_collects.user_id', '=', $data['user_id']]])
                ->where($where)
                ->select("*")
                ->get();
        }else{
            if (isset($data['title']) && !empty($data['title'])) {
                $ids = $this->getCollectIdByTitle($data);
                $where[] = [function ($query) use ($ids) {
                    $query->whereIn('id', $ids);
                }];
            }
            $where[] = ['user_id','=',$data['user_id']];
            $res = $this->where($where)->where([['user_id','=',$data['user_id']]])->orderByDesc("id")->get();
            if (!empty($res)) {
                foreach ($res as $k => $v) {
                    if ($v->type == 1) { //课程
                        $course = (new Course())->where([['id', '=', $v->course_id]])->first();
                        if (empty($course)) {
                            (new CourseCollect())->where([['id', '=', $v->id]])->delete();
                            continue;
                        }
                        $res[$k]->course_title = $course->course_title;
                        $res[$k]->buy_num = $course->buy_num;
                        $res[$k]->course_price = $course->course_price;
                        $res[$k]->course_score = $course->course_score;
                        $res[$k]->course_img = $host::getHttpHost() . 'upload/' . $course->course_img;
                        $res[$k]->cate_name = $courseCategory->where([['id', '=', $course->course_sort_id]])->value("classify_name");
                    } elseif ($v->type == 2) {
                        $course = (new ProductGoods())->where([['id', '=', $v->course_id]])->first();
                        if (empty($course)) {
                            (new CourseCollect())->where([['id', '=', $v->id]])->delete();
                            continue;
                        }
                        $res[$k]->product_name = $course->product_name;
                        $res[$k]->product_image = $host::getHttpHost() . '/upload/' . $course->product_image;
                        $res[$k]->product_retail_price = $course->product_retail_price;
                        $res[$k]->product_sales = $course->product_sales;
                        $res[$k]->product_score = $course->product_score;
                        $res[$k]->cate_name = $productSort->where([['id', '=', $course->product_sort_id]])->value("sort_name");
                    } elseif ($v->type == 3) {
                        $course = (new Article())->where([['id', '=', $v->course_id]])->first();
                        if (empty($course)) {
                            (new CourseCollect())->where([['id', '=', $v->id]])->delete();
                            continue;
                        }
                        $res[$k]->article_title = $course->article_title;
                        $res[$k]->art_img = $host::getHttpHost() . '/upload/' . $course->art_img;
                        $res[$k]->article_score = $course->article_score;
                        $res[$k]->classify_name = $clinic->where([['id', '=', $course->clinic_cate_id]])->value("classify_name");
                    }
                }
            }
        }
        if (!empty($res)) {
            $res = $res->toArray();
            $tool = new Tool();
            if (isset($data['type']) && $data['type'] == 1) {
                foreach ($res as $k => $v) {
                    $res[$k]['course_img'] = $tool->addHostToImage($v['course_img']);
                    $res[$k]['cate_name'] =$courseCategory->where([['id','=',$v['course_sort_id']]])->value("classify_name");
                }
            } elseif (isset($data['type']) && $data['type'] == 2) {
                foreach ($res as $k => $v) {
                    $res[$k]['product_image'] = $tool->addHostToImage($v['product_image']);
                    $res[$k]['cate_name'] =$productSort->where([['id','=',$v['product_sort_id']]])->value("sort_name");
                }
            }elseif (isset($data['type']) && $data['type'] == 3) {
                foreach ($res as $k => $v) {
                    $res[$k]['art_img'] = $tool->addHostToImage($v['art_img']);
                    $res[$k]['classify_name'] =$clinic->where([['id','=',$v['clinic_cate_id']]])->value("classify_name");
                }
            }
        }
        $res = $this::array_group_by($res);
        return $res;
    }




    /****
     * @param $data
     * @return mixed
     * 获取收藏列表(android使用
     */
    public function getCollectListDataAndroid($data)
    {
        $where = [];
        $host = new Url();
        $courseCategory =  new CourseCategory();
        $productSort =  new ProductSort();
        $clinic =  new ClinicCategory();
        if (isset($data['type']) && !empty($data['type'])) {
            $where[] = ['c_course_collects.type', '=', $data['type']];
        }
        if (isset($data['collect_type']) && !empty($data['collect_type'])) {
            $where[] = ['c_course_collects.collect_type', '=', $data['collect_type']];
        }
        if (isset($data['type']) && $data['type'] == 1) {
            if (isset($data['title']) && !empty($data['title'])) {
                $where[] = ['c.course_title', 'like', '%' . $data['title'] . '%'];
            }
            $res = $this->join('c_courses as c', 'c.id', '=', 'c_course_collects.course_id')
                ->where([['c_course_collects.user_id', '=', $data['user_id']]])
                ->where($where)
                ->select("*")
                ->get();
        } elseif (isset($data['type']) && $data['type'] == 2) {
            if (isset($data['title']) && !empty($data['title'])) {
                $where[] = ['c.product_name', 'like', '%' . $data['title'] . '%'];
            }
            $res = $this->join('c_product_goods as c', 'c.id', '=', 'c_course_collects.course_id')
                ->where([['c_course_collects.user_id', '=', $data['user_id']]])
                ->where($where)
                ->select("*")
                ->get();
        }elseif (isset($data['type']) && $data['type'] == 3) {
            if (isset($data['title']) && !empty($data['title'])) {
                $where[] = ['c.article_title', 'like', '%' . $data['title'] . '%'];
            }
            $res = $this->join('c_articles as c', 'c.id', '=', 'c_course_collects.course_id')
                ->where([['c_course_collects.user_id', '=', $data['user_id']]])
                ->where($where)
                ->select("*")
                ->get();
        }else{
            if (isset($data['title']) && !empty($data['title'])) {
                $ids = $this->getCollectIdByTitle($data);
                $where[] = [function ($query) use ($ids) {
                    $query->whereIn('id', $ids);
                }];
            }
            $res = $this->where($where)->where([['user_id','=',$data['user_id']]])->orderByDesc("id")->get();
            if (!empty($res)) {
                foreach ($res as $k => $v) {
                    if($v->type ==1){ //课程
                        $course = (new Course())->where([['id','=',$v->course_id]])->first();
                        if (empty($course)) {
                            (new CourseCollect())->where([['id', '=', $v->id]])->delete();
                            continue;
                        }
                        $res[$k]->course_title = $course->course_title;
                        $res[$k]->buy_num = $course->buy_num;
                        $res[$k]->course_price = $course->course_price;
                        $res[$k]->course_score = $course->course_score;
                        $res[$k]->course_img =$host::getHttpHost().'upload/'.  $course->course_img;
                        $res[$k]->cate_name =$courseCategory->where([['id','=',$course->course_sort_id]])->value("classify_name");
                    }elseif ($v->type ==2){
                        $course = (new ProductGoods())->where([['id','=',$v->course_id]])->first();
                        if (empty($course)) {
                            (new CourseCollect())->where([['id', '=', $v->id]])->delete();
                            continue;
                        }
                        $res[$k]->product_name = $course->product_name;
                        $res[$k]->product_image = $host::getHttpHost().'/upload/'.$course->product_image;
                        $res[$k]->product_retail_price = $course->product_retail_price;
                        $res[$k]->product_sales = $course->product_sales;
                        $res[$k]->product_score = $course->product_score;
                        $res[$k]->cate_name =$productSort->where([['id','=',$course->product_sort_id]])->value("sort_name");
                    }elseif ($v->type ==3){
                        $course = (new Article())->where([['id','=',$v->course_id]])->first();
                        if (empty($course)) {
                            (new CourseCollect())->where([['id', '=', $v->id]])->delete();
                            continue;
                        }
                        $res[$k]->article_title = $course->article_title;
                        $res[$k]->art_img = $host::getHttpHost().'/upload/'.$course->art_img;
                        $res[$k]->article_score = $course->article_score;
                        $res[$k]->classify_name =$clinic->where([['id','=',$course->clinic_cate_id]])->value("classify_name");
                    }
                }
            }
        }
        if (!empty($res)) {
            $res = $res->toArray();
            $tool = new Tool();
            if (isset($data['type']) && $data['type'] == 1) {
                foreach ($res as $k => $v) {
                    $res[$k]['course_img'] = $tool->addHostToImage($v['course_img']);
                    $res[$k]['cate_name'] =$courseCategory->where([['id','=',$v['course_sort_id']]])->value("classify_name");
                }
            } elseif (isset($data['type']) && $data['type'] == 2) {
                foreach ($res as $k => $v) {
                    $res[$k]['product_image'] = $tool->addHostToImage($v['product_image']);
                    $res[$k]['cate_name'] =$productSort->where([['id','=',$v['product_sort_id']]])->value("sort_name");
                }
            }elseif (isset($data['type']) && $data['type'] == 3) {
                foreach ($res as $k => $v) {
                    $res[$k]['art_img'] = $tool->addHostToImage($v['art_img']);
                    $res[$k]['classify_name'] =$clinic->where([['id','=',$v['clinic_cate_id']]])->value("classify_name");
                }
            }
        }
        return $res;
    }


    /**
     * @param $data
     * @return array
     */
    public function getCollectIdByTitle($data)
    {
        $where = [];
        $where[] = ['collect_type', '=', $data['collect_type']];
        $article_data = [];
        $goods_data = [];
        $course_data = [];
        $article_id = $this->join('c_articles as c', 'c.id', '=', 'c_course_collects.course_id')
            ->where([['c_course_collects.user_id', '=', $data['user_id']]])
            ->where([['c_course_collects.type', '=', 3]])
            ->where([['c.article_title', 'like', '%' . $data['title'] . '%']])
            ->where($where)
            ->pluck("c_course_collects.id");
        if(!empty($article_id)){
            $article_data = $article_id->toArray();
        }
        $goods_ids = $this->join('c_product_goods as c', 'c.id', '=', 'c_course_collects.course_id')
            ->where([['c_course_collects.user_id', '=', $data['user_id']]])
            ->where([['c_course_collects.type', '=', 2]])
            ->where([['c.product_name', 'like', '%' . $data['title'] . '%']])
            ->where($where)
            ->pluck("c_course_collects.id");
        if(!empty($goods_ids)){
            $goods_data = $goods_ids->toArray();
        }
        $course_ids = $this->join('c_courses as c', 'c.id', '=', 'c_course_collects.course_id')
            ->where([['c_course_collects.user_id', '=', $data['user_id']]])
            ->where([['c_course_collects.type', '=', 1]])
            ->where([['c.course_title', 'like', '%' . $data['title'] . '%']])
            ->where($where)
            ->pluck("c_course_collects.id");
        if(!empty($course_ids)){
            $course_data = $course_ids->toArray();
        }
        return   array_unique(array_merge($article_data, $goods_data,$course_data));
    }
    
    

    public function getInfos($data)
    {
        return $this
            ->where("course_id", '=', $data['course_id'])
            ->where("user_id", '=', $data['user_id'])
            ->where("work_id", '=', $data['work_id'])
            ->where("type", '=', $data['type'])
            ->where("collect_type", '=', $data['collect_type'])
            ->first();
    }

    /***
     * @param $list
     * @return array
     * 分组排序
     */
    public static function array_group_by($list)
    {
        $newArray = array();
        foreach ($list as $v) {
            $newArray[$v['ins_times']][] = $v;
        }
        return $newArray;
    }

}

